var system = null;
var searchResultsCount = 50;
var artistReturnCount = 50;

function startSystem() {
    system = new Exit66Jukebox(document.getElementById('status'),
    document.getElementById('navbar'),
    document.getElementById('mainarea'));
    
    var myGlobalHandlers = {
		onCreate: function(){
			Element.show('systemWorking');
		},

		onComplete: function() {
			if(Ajax.activeRequestCount == 0){
				Element.hide('systemWorking');
			}
		}
	};

	Ajax.Responders.register(myGlobalHandlers);
}

function loadStatus() {
    system.loadStatus();
}

function loadQueue() {
    system.loadQueue();
}

function resizeSystem() {
    system.resize();
}

function Exit66Jukebox(oStatus, oNav, oMain) {
    this._statusContainer = oStatus;
    this._navContainer = oNav;
    this._mainContainer = oMain;
    
    this._welcomeArea = null;
    this._mainArtistTable = null;
    
    this._mainAlbumArea = null;
    
    this._searchArea = null;
    this._searchResultsTable = null;
    this._init();
    
    this._lastTrackStatusId = null;
    this._lastQueueHTML = "";
    
    this._showAlbumCovers = true;
    //if (window.ActiveXObject) {
    //    this._showAlbumCovers = false;
    //}
    
    this._statusArea = null;
    this._queueDiv = null;
    this._nowPlayingDiv = null;
    
    this._createStatusArea();
    
    this.loadStatus();
    //this._statusIntervalID = setInterval("loadStatus();", 10000);
    
    this.loadQueue();
    this._queueIntervalID = setInterval("loadQueue();", 10000);
    
    this.resize();
}

Exit66Jukebox.prototype._init = function() {
    var oThis = this;
    var nav = document.createElement('table');
    var navBody = document.createElement('tbody');
    var navRow = document.createElement('tr');
    var sideCol = document.createElement('td');
   
    sideCol.className = 'leftSide';
    sideCol.appendChild(document.createTextNode("\u00a0"));
    navRow.appendChild(sideCol);
    
    function createNavItem(label, className) {
        var item = document.createElement('td');

        if (!className) {
            className = 'nav';
        }
        
        var mouseOverFunction = function(e, style) {
        return function() {
            e.className = style;
        }
        }(item, className + 'Hover');
        var mouseOutFunction = function(e, style) {
            return function() {
                e.className = style;
            }
        }(item, className);
        item.appendChild(document.createTextNode(label));        
        item.onmouseover = mouseOverFunction;
        item.onmouseout = mouseOutFunction
        item.className = className;
        item.style.cursor = 'pointer';
        item.style.margin = '.1em';
        
        return item;
    }
    
    function appendNavItem(parent, label, searchString, className) {
        var item = createNavItem(label, className);

        var clickFunction = function(e) {
            return function() {
                oThis._searchArtists(e); 
            }
        }(searchString);
        item.onclick = clickFunction;
        parent.appendChild(item);
    }
    
    homeItem = createNavItem("\u00a0", "navHome");
    f = function() {
        oThis.startOver();
    };
    homeItem.onclick = f;
    navRow.appendChild(homeItem);
    
    searchItem = createNavItem("\u00a0", "navSearch");
    f = function() {
        oThis.startSearch();
    };
    searchItem.onclick = f;
    navRow.appendChild(searchItem);
    
    appendNavItem(navRow, '#', '@num');
    for (counter = 65; counter < 91; counter++) {
        var currentLetter = String.fromCharCode(counter);
        appendNavItem(navRow, currentLetter, currentLetter + '%');
    } 
    sideCol = document.createElement('td');
    sideCol.className = 'rightSide';
    sideCol.appendChild(document.createTextNode("\u00a0"));
    navRow.appendChild(sideCol);    
    
    navBody.appendChild(navRow);
    nav.appendChild(navBody);    
    this._navContainer.appendChild(nav);
    
    this._createWelcomeArea();

    
}

Exit66Jukebox.prototype.startOver = function() {    
    this._clearBrowseArea();

    if (this._welcomeArea) {
        this._welcomeArea.addToParent(this._mainContainer);
    }
    else {
        this._createWelcomeArea();
    }
    
}

Exit66Jukebox.prototype.startSearch = function() {
    this._clearBrowseArea();
    
    var oThis = this;
        
    var searchField = createElement('input', 'searchField');
    
    var clickArtist = function(searchField) {
        return function() {
            oThis._processSearch(searchField, false, true, false, 0, searchResultsCount);
        }
    }(searchField);            
    
    var clickAlbum = function(searchField) {
        return function() {
            oThis._processSearch(searchField, true, false, false, 0, searchResultsCount);
        }
    }(searchField);
    
    var clickTrack = function(searchField) {
        return function() {
            oThis._processSearch(searchField, false, false, true, 0, searchResultsCount);
        }
    }(searchField);
    
    var pressEnter = function(searchField) {
        return function(e) {
            var key = window.event ? event.keyCode : e.keyCode;
            if (key == 13) {
                oThis._processSearch(searchField, false, false, true, 0, searchResultsCount);
            }
        }
    }(searchField);
    
    if (this._welcomeArea) {
        this._welcomeArea.removeFromParent();
    }
    
    this._searchArea = new Exit66RoundedBox("search");
    var label = document.createElement('div');
    label.className = 'header';
    label.appendChild(document.createTextNode('Search'));
    this._searchArea.addToContent(label);

    searchField.type = 'text';
    searchField.style.width = "100%";
    searchField.onkeydown = pressEnter;
    this._searchArea.addToContent(searchField);
    this._searchArea.addToContent(document.createElement('br'));
    
    var button = createElement('input', 'searchArtist');
    button.type = 'button';
    button.style.marginRight = "2%";
    button.style.width = "32%";
    button.value = 'Search\nArtists';
    button.className = "button";
    button.onclick = clickArtist;
    this._searchArea.addToContent(button);
    
    button = createElement('input', 'searchAlbum');
    button.type = 'button';
    button.style.marginRight = "2%";
    button.style.width = "32%";
    button.value = 'Search\nAlbums';
    button.className = "button";
    button.onclick = clickAlbum;
    this._searchArea.addToContent(button);
    
    button = document.createElement('input');
    button.name = 'searchTrack';
    button.type = 'button';
    button.style.width = "32%";
    button.value = 'Search\nTracks';
    button.className = "button";
    button.onclick = clickTrack;
    this._searchArea.addToContent(button);
    
   
    this._searchArea.addToParent(this._mainContainer);
    
    var columnDetails = new Array({className: 'artistName'}, 
        {className: 'albumName'}, {className: 'trackName'});
    this._searchResultsTable = new Exit66Table('searchResults', columnDetails);
    
    this._searchResultsTable.addToParent(this._mainContainer);
    
    this._resizeSearchArea();
}

Exit66Jukebox.prototype._processSearch = function(searchField, searchAlbum, searchArtist, searchTrack, start, count) {
    //alert(document.body.innerHTML);
    // searchField = document.getElementsByName('searchField')[0];
    
    if (searchField.value != '') {
        this._searchList('%' + searchField.value + '%', searchArtist, 
            searchAlbum, searchTrack, start, count);
    }
    else {
        alert('Please enter a phrase to search for.');
    }
}

Exit66Jukebox.prototype._processSearchResults = function(xml, search, searchArtists, searchAlbums, 
    searchTracks, start, count) {
    var resultsTable = this._searchResultsTable;
    resultsTable.clearAllRows();
    resultsTable.addRow(new Array({value: 'Artist', className: 'tableHeader'}, 
        {value: 'Album', className: 'tableHeader'}, {value: 'Track', className: 'tableHeader'}));

    var rootNode = getXmlResponseNode(xml);
    var oThis = this;
    
    var rowCount = 0;
                
    if ((rootNode) && (rootNode.hasChildNodes())) {
        var currentNode = rootNode.firstChild;
        while (currentNode) {
	    rowCount++;
            var trackId = getNodeText(currentNode.getElementsByTagName("trackId")[0]);
            var artistName = getNodeText(currentNode.getElementsByTagName("artistName")[0]);
            var albumName = getNodeText(currentNode.getElementsByTagName("albumName")[0]);
            var trackName = getNodeText(currentNode.getElementsByTagName("trackName")[0]);
            var clickFunction = function(trackId) {
                return function() {
                    oThis.requestTrack(trackId);
                }
            }(trackId);
            resultsTable.addRow(new Array({value: artistName}, 
                {value: albumName}, {value: trackName}), clickFunction);
            currentNode = currentNode.nextSibling;
        }
    }
    else {
        resultsTable.addRow(new Array({value: 'No results found', colSpan: 3}));
    }
    
    var needsFooter = false;
    
    if (start != 0) {
        var pageBack = function(search, searchArtists, searchAlbums, 
            searchTracks, start, count) {
            return function() {
                oThis._searchList(search, searchArtists, searchAlbums, 
                    searchTracks, start, count);
            }
        }(search, searchArtists, searchAlbums, searchTracks, start-count, count);
        backCol = {value: "<< Back", className: 'tableHeaderButton', clickFunction: pageBack};
	needsFooter = true;
    }
    else {
	backCol = {value: "&nbsp;", className: 'tableHeader'};
    }
    
    if ((rootNode) && (rootNode.hasChildNodes()) && (rowCount==count)) {
        var pageNext = function(search, searchArtists, searchAlbums, 
            searchTracks, start, count) {
            return function() {
                oThis._searchList(search, searchArtists, searchAlbums, 
                    searchTracks, start, count);
            }
        }(search, searchArtists, searchAlbums, searchTracks, start+count, count);
        nextCol = {value: "More >>", className: 'tableHeaderButton', clickFunction: pageNext};
	needsFooter = true;
    }
    else {
        nextCol = {value: "&nbsp;", className: 'tableHeader'};
    }
    
    if (needsFooter) {
        resultsTable.addRow(new Array(backCol, {value: "&nbsp;", className: 'tableHeader'},
		nextCol), null, 'tableHeaderButton', true);
    }
}

Exit66Jukebox.prototype._searchList = function(search, searchArtists, searchAlbums, 
    searchTracks, start, count) {
    var oThis = this;
    
    var f = function(search, searchArtists, searchAlbums, searchTracks, start, count) {
        return function(req) {
            oThis._processSearchResults(req.responseXML, search, searchArtists, 
                    searchAlbums, searchTracks, start, count);
        }
    } (search, searchArtists, searchAlbums, searchTracks, start, count);
    
    search = replace(search, '%', '%25');
    var params = "value=" + search;
    var sep = "&";
    if (searchArtists) {
        params += sep + "artists=1";
        sep = "&";
    }
    if (searchAlbums) {
        params += sep + "albums=1";
        sep = "&";
    }
    if (searchTracks) {
        params += sep + "tracks=1";
        sep = "&";
    }
    
    var req = new Ajax.Request("/ws/search",
        {
            method: "post", 
            parameters: params + sep + "start=" + start + "&count=" + count,
            onComplete: f
        });
    
}

Exit66Jukebox.prototype._clearBrowseArea = function() {
    if (this._searchArea) {
        this._searchArea.removeFromParent();
        this._searchArea = null;
        this._searchResultsTable.removeFromParent();
        this._searchResultsTable = null;
    }
    if (this._mainArtistTable) {
        this._mainContainer.removeChild(this._mainArtistTable.getElement());
        this._mainArtistTable = null;
    }
    if (this._mainAlbumArea) {
        this._mainContainer.removeChild(this._mainAlbumArea);
        this._mainAlbumArea = null;
    }
}

Exit66Jukebox.prototype._resizeSearchArea = function() {
    if (this._searchArea) {
        this._searchArea.setHeight(document.body.clientHeight - 
            (this._statusContainer.offsetHeight + 
            this._navContainer.offsetHeight) - 6);
        this._searchResultsTable.setHeight(document.body.clientHeight - 
            (this._statusContainer.offsetHeight + 
            this._navContainer.offsetHeight) - 6);
    }
}

Exit66Jukebox.prototype._createWelcomeArea = function() {
    if (!this._welcomeArea) {
        this._welcomeArea = new Exit66RoundedBox("welcome");
        
        img = document.createElement('img');
        img.src = '/images/jblogo.gif';
        img.width = 400;
        img.height = 320;
        this._welcomeArea.addToContent(img);

        header = document.createElement('div');
        header.className = 'header';
        header.innerHTML = 'Welcome to Exit 66 Jukebox';
        this._welcomeArea.addToContent(header);
        
        instructions = document.createElement('div');
        instructions.className = 'instructions';
        
        instructions.appendChild(document.createTextNode('How to use this jukebox:'));
        
        instructions.appendChild(document.createElement('br'));        
        
        instructions.appendChild(document.createTextNode('1) Select a letter above to browse ' + 
            'for artists with that name.'));
        
        instructions.appendChild(document.createElement('br'));        
        
        instructions.appendChild(document.createTextNode('2) A list of artists from which you ' + 
            'can select will appear to the left.'));
        
        instructions.appendChild(document.createElement('br'));        
        
        instructions.appendChild(document.createTextNode('3) By clicking on an artists name, ' + 
            'you will see their albums listed on the right.'));        
        
        instructions.appendChild(document.createElement('br'));        
        
        instructions.appendChild(document.createTextNode('4) Clicking on an album cover or ' + 
            'title will let you see the songs on that album.'));        
        
        instructions.appendChild(document.createElement('br'));        
        
        instructions.appendChild(document.createTextNode('5) You can then click on an song ' + 
            'title to request it.'));       

        this._welcomeArea.addToContent(instructions);
        this._welcomeArea.addToParent(this._mainContainer);
    }
}

Exit66Jukebox.prototype.resize = function() {
    this._resizeWelcomeArea();
    this._resizeSearchArea();
    this._resizeArtistDiv();
    this._resizeAlbumArea();
}

Exit66Jukebox.prototype._resizeWelcomeArea = function() {
    if (this._welcomeArea) {
        this._welcomeArea.setHeight(document.body.clientHeight - 
            (this._statusContainer.offsetHeight + 
            this._navContainer.offsetHeight) - 6);
    }
}

Exit66Jukebox.prototype._resizeArtistDiv = function() {
    if (this._mainArtistTable) {
        this._mainArtistTable.setHeight(document.body.clientHeight - 
            (this._statusContainer.offsetHeight + 
            this._navContainer.offsetHeight) - 6);
    }
}

Exit66Jukebox.prototype._resizeAlbumArea = function() {
    if (this._mainAlbumArea) {
        this._mainAlbumArea.style.height = document.body.clientHeight - 
            (this._statusContainer.offsetHeight + 
            this._navContainer.offsetHeight) - 6;
    }
}

Exit66Jukebox.prototype._createStatusArea = function() {
    this._statusArea = new Exit66RoundedBox('status');
    this._statusArea.addToParent(this._statusContainer);
    this._queueDiv = new Exit66Scroller('queue');
    this._queueDiv.onScrollComplete = loadQueue;
    this._nowPlayingDiv = new Exit66Scroller('nowPlaying');
    //this._nowPlayingDiv.onScrollComplete = loadStatus;
    this._statusArea.addToContent(this._nowPlayingDiv.getElement());
    this._statusArea.addToContent(this._queueDiv.getElement());
}

Exit66Jukebox.prototype._searchArtists = function(search, start) {
    var oThis = this;
    
    if (start == null)
        start = 0;

    var f = function(search, start) {
        return function(req) {
            oThis._loadArtists(req.responseXML, null, search, start);
        }
    } (search, start);
    
    var req = new Ajax.Request("/ws/artistlist/" + search,
        { 
            method: "post", 
            parameters: "start=" + start + "&count=" + artistReturnCount, 
            onComplete: f 
        });
}

Exit66Jukebox.prototype._selectArtist = function(artistId, albumId) {
    var oThis = this;
    
    var f = function(albumId) {
        return function(req) {
            oThis._loadArtists(req.responseXML, albumId);
        }
    } (albumId);
    
    var req = new Ajax.Request("/ws/artist/" + artistId,
        {
            method: "post",
            onComplete: f
        });
}

Exit66Jukebox.prototype._createArtistArea = function() {
    if (this._welcomeArea) {
        this._welcomeArea.removeFromParent();
    }
    if (this._searchArea) {
        this._searchArea.removeFromParent();
        this._searchArea = null;
        this._searchResultsTable.removeFromParent();
        this._searchResultsTable = null;
    }
    var columnDetails = new Array({className: 'artistName'});
    this._mainArtistTable = new Exit66Table('artistList', columnDetails);
    this._mainArtistTable.setHeader(['Artists']);
    this._mainArtistTable.addToParent(this._mainContainer);
    
    this._resizeArtistDiv();
}

Exit66Jukebox.prototype._loadArtists = function(xml, expandAlbumId, search, start) {
    if (!this._mainArtistTable) {
        this._createArtistArea();
    }
    
    var artistTable = this._mainArtistTable;
    if ((start == null) || (start == 0)) 
        artistTable.clearAllRows();
    
    var noArtistDiv = null;
            
    var rootNode = getXmlResponseNode(xml);
    var oThis = this;
    var count = 0;
                
    if ((rootNode) && (rootNode.hasChildNodes())) {
        var currentNode = rootNode.firstChild;
        while (currentNode) {
            var artistName = getNodeText(currentNode.getElementsByTagName("name")[0]);
            var artistId = getNodeText(currentNode.getElementsByTagName("id")[0]);
            var clickFunction = function(artistId, artistName) {
                return function() {
                    oThis._searchAlbums(artistId, -1, expandAlbumId, artistName); 
                }
            }(artistId, artistName);
            artistTable.addRow(new Array({value: artistName}), clickFunction);
            currentNode = currentNode.nextSibling;
            count += 1;
        }
        if ((start != null) && (count == artistReturnCount)) {
            this._searchArtists(search, start + artistReturnCount);
        }
    }
    else {
        if ((start == null) || (start == 0))
            artistTable.addRow(new Array({value: 'No artists found'}));
    }
    
    if (this._mainAlbumArea) {
        removeChild(this._mainContainer, this._mainAlbumArea);
        this._mainAlbumArea = null;
    }
}

Exit66Jukebox.prototype._searchAlbums = function(artistId, albumId, expandAlbumId, artistName) {
    var oThis = this;
    
    var f = function(artistId, expandAlbumId, artistName) {
        return function(req) {
            oThis._loadAlbums(req.responseXML, artistId, expandAlbumId, artistName);
        } 
    } (artistId, expandAlbumId, artistName);

    var req = new Ajax.Request("/ws/albumlist/artist/" + artistId, 
        {
            method: "post",
            onComplete: f,
            onFailure: errFunc
        });            
}

Exit66Jukebox.prototype._loadAlbums = function(xml, artistId, expandAlbumId, artistName) {
    var albumArea = document.createElement('div');
    albumArea.className = 'albumSide';
    	
    var rootNode = getXmlResponseNode(xml);
    var oThis = this;
              
    var trackTable;
    var sArtist;    

    if ((rootNode) && (rootNode.hasChildNodes())) {
        var currentAlbum = rootNode.firstChild;
        while (currentAlbum) {
            var albumName = getNodeText(currentAlbum.getElementsByTagName("name")[0]);
            var albumId = getNodeText(currentAlbum.getElementsByTagName("id")[0]);
            var artistAlbumId = getNodeText(currentAlbum.getElementsByTagName("multipleArtistId")[0]);
            var artistCount = getNodeText(currentAlbum.getElementsByTagName("artistCount")[0]);
            
            var clearBreak = this._getClearBreak();
                        
            var albumSegment = new Exit66RoundedBox('album');
            var headerDiv = document.createElement('div');
            var artistSpan = document.createElement('div');
            var albumSpan = document.createElement('div');
            var albumImage = document.createElement('img');
            var albumImageDiv = document.createElement('div');
            var hasOtherArtists = false;
            albumImageDiv.className = 'browseCover';
            albumImage.src = '/showimg?albumid=' + albumId;
            albumImage.className = 'browseCover';

            artistSpan.className = 'artistName';
            albumSpan.className = 'albumName';
            albumSpan.innerHTML = albumName;
                        
            if (artistAlbumId != -1) {
                artistSpan.innerHTML = getNodeText(currentAlbum.getElementsByTagName("name")[0]);
                hasOtherArtists = true;
            }
            else {
                if (artistCount > 1) {
                    artistSpan.innerHTML = "Various Artists";
                    hasOtherArtists = true;
                }
                else {
                    artistSpan.innerHTML = artistName;
                }
            }
            
            var f = function(albumId, artistId, albumSegment, hasOtherArtists) {
                return function() {
                    if (albumSegment.trackTable) {
                        albumSegment.trackTable.toggleVisibility();
                    }
                    else {
                        oThis._searchTracks(albumId, artistId, albumSegment, hasOtherArtists);
                    }
                }
            }(albumId, artistId, albumSegment, hasOtherArtists);
            artistSpan.onclick = f;
            albumSpan.onclick = f;
            albumImage.onclick = f;
            albumSegment.setOnClick(f);
            artistSpan.style.cursor = 'pointer';
            albumSpan.style.cursor = 'pointer';
            albumImage.style.cursor = 'pointer';
            if (this._showAlbumCovers) {
                albumImageDiv.appendChild(albumImage);
                headerDiv.appendChild(albumImageDiv);
                //albumSegment.addToContent(albumImageDiv);
            }
            //albumSegment.addToContent(artistSpan);
            //albumSegment.addToContent(albumSpan);
            headerDiv.appendChild(artistSpan);
            headerDiv.appendChild(albumSpan);
            headerDiv.appendChild(clearBreak);
            albumSegment.addToContent(headerDiv);
            
            albumSegment.addToParent(albumArea);
            
            currentAlbum = currentAlbum.nextSibling;
        }
    }
    else {

    }
    
    if (this._mainAlbumArea) {
        this._mainContainer.removeChild(this._mainAlbumArea);
    }
    this._mainContainer.appendChild(albumArea);
    this._mainAlbumArea = albumArea;
    this._resizeAlbumArea();
}

Exit66Jukebox.prototype._searchTracks = function(albumId, artistId, albumArea, hasOtherArtists) {
    var oThis = this;
    
    var f = function(albumId, artistId, albumArea, hasOtherArtists) {
        return function(req) {
            oThis._loadTracks(req.responseXML, albumId, artistId, albumArea, hasOtherArtists);
        }
    } (albumId, artistId, albumArea, hasOtherArtists);
    
    var req = new Ajax.Request("/ws/tracklist/album/" + albumId,
        {
            method: "post",
            onComplete: f
        });
}

Exit66Jukebox.prototype._loadTracks = function(xml, albumId, artistId, albumArea, hasOtherArtists) {
    var rootNode = getXmlResponseNode(xml);
    var oThis = this;
              
    var trackTable;
            
    if ((rootNode) && (rootNode.hasChildNodes())) {
        
        trackTable = new Exit66Table('trackList', 
            new Array({className: 'trackNumber'}, 
                {className: 'trackName'}));
        
        trackTable.setTableVisibility(false);
        var trackList = rootNode.getElementsByTagName("track");
        var trackLabel = '';
                
        for (i=0; i<trackList.length; i++) {
            currentTrack = trackList[i];
            var eventOdd = "";
            if ((i % 2) == 0) {
                evenOdd = "Even";
            } 
            else {
                evenOdd = "Odd";
            }
            var trackName = getNodeText(currentTrack.getElementsByTagName("name")[0]);
            var trackId = getNodeText(currentTrack.getElementsByTagName("id")[0]);
            var trackArtistId = getNodeText(currentTrack.getElementsByTagName("artistId")[0]);
            var trackNumber = getNodeText(currentTrack.getElementsByTagName("number")[0]);
                            
            var f = function(e) {
                return function() {
                    oThis.requestTrack(e);
                }
            }(trackId);
    
            if ((trackNumber == "0") || (trackNumber == "")) {
                trackNumber = "&nbsp;"
            }
    
            if (!hasOtherArtists)
                trackLabel = trackName;
            else
                trackLabel = trackName + ' - ' + getNodeText(currentTrack.getElementsByTagName("artistName")[0]);
                
            trackRow = trackTable.addRow(new Array({value: trackNumber}, {value: trackLabel}), f);
                            
            if ((hasOtherArtists) && (trackArtistId != artistId)) {
                trackRow.style.display = 'none';
            }                
        }
        
        if (hasOtherArtists) {
            var f = function(e) {
                return function() {
                    oThis._showAllRows(e); 
                }
            }(trackTable);
            trackTable.addRow(new Array({value: 'This album also has tracks by ' + 
                'other artists.  Click here to see them all.', 
                className: 'otherTrackMessage', colSpan: 2}), 
                f, 'otherTrackMessage');
        } 
        
        var f = function(e) {
            return function() {
                oThis.requestAlbum(e);  
            }
        }(albumId);
        trackRow = trackTable.addRow(new Array({value: 'Request entire album.', 
            className: 'requestAlbum', colSpan: 2}), f, 'requestAlbum');
        if (hasOtherArtists) {
            trackRow.style.display = 'none';
        }
        
        albumArea.trackTable = trackTable;
        trackTable.addToParent(albumArea.getContentBox()); 
        trackTable.toggleVisibility();
    }
}

Exit66Jukebox.prototype._showAllRows = function(table) {
    table = table.getRowParent();
    row = table.firstChild;
    while (row) {
        if (row.className.indexOf('otherTrackMessage') != 0) {
            // row.style.display = 'table-row';
            row.style.display = '';
        }
        else {
            row.style.display = 'none';
        }
        row = row.nextSibling;
    }
}

Exit66Jukebox.prototype.loadStatus = function() {
    var element = this._nowPlayingDiv.getContentBox();
    var oThis = this;
    
    var f = function(req) {
        var rootNode = getXmlResponseNode(req.responseXML);
        
        if ((rootNode) && (rootNode.hasChildNodes())) {
            var trackNode = rootNode.getElementsByTagName("track")[0];
            var trackId = getNodeText(trackNode.getElementsByTagName("id")[0]);
            if (trackId != oThis._lastTrackStatusId) { 
                oThis._lastTrackStatusId = trackId;
                var trackTextNode = trackNode.getElementsByTagName("name")[0];
                var name = getNodeText(trackTextNode);
                var artistName = getNodeText(trackNode.getElementsByTagName("artistName")[0]);
                var artistId = getNodeText(trackNode.getElementsByTagName("artistId")[0]);
                var albumName = getNodeText(trackNode.getElementsByTagName("albumName")[0]);
                var albumId = getNodeText(trackNode.getElementsByTagName("albumId")[0]);
        
                element.innerHTML = '';
                if (oThis._showAlbumCovers) {
                    var albumImage = document.createElement('img');
                    albumImage.src = '/showimg?albumid=' + albumId;
                    albumImage.className = 'statusCover';
                    element.appendChild(albumImage);
                }
                
                p = document.createElement('p');
                p.style.margin = '0';
                p.style.fontWeight = 'bold';
                p.style.marginLeft = '110px';
                p.appendChild(document.createTextNode("Now Playing:"));
                element.appendChild(p);
                
                p = document.createElement('p');
                p.style.margin = '0';
                p.style.marginLeft = '110px';
                p.appendChild(document.createTextNode(name));
                element.appendChild(p);
                
                p = document.createElement('p');
                p.style.margin = '0';
                p.style.marginLeft = '110px';
                link = document.createElement('a');
                link.appendChild(document.createTextNode(artistName));
                p.appendChild(link);
                element.appendChild(p);
                
                p = document.createElement('p');
                p.style.margin = '0';
                p.style.marginLeft = '110px';
                link = document.createElement('a');
                link.appendChild(document.createTextNode(albumName));
                p.appendChild(link);
                element.appendChild(p);
                
                document.title = 'Exit 66 Jukebox - Now Playing: ' + name + ' by ' + artistName;
                
            }
        }
        else {
            if (oThis._lastTrackStatusId != -1) {
                element.innerHTML = '';
                p = document.createElement('p');
                p.style.margin = '0';
                p.style.marginLeft = '2px';
                p.style.fontWeight = 'bold';
                p.appendChild(document.createTextNode('Welcome to Exit 66 Jukebox'));
                element.appendChild(p);
                
                p = document.createElement('p');
                p.style.margin = '0';
                p.style.fontWeight = 'bold';
                p.style.marginLeft = '2px';
                p.appendChild(document.createTextNode("Please request a song..."));
                element.appendChild(p);
                oThis._lastTrackStatusId = -1;
                
                document.title = 'Exit 66 Jukebox';
            }
        }
    };
    
    var req = new Ajax.Request("/ws/currenttrack", 
        {
            method: "post",
            onComplete: f
        });
}

Exit66Jukebox.prototype.loadQueue = function() {
    var element = this._queueDiv.getContentBox();
    var oThis = this;
    var f = function(req) {
        var rootNode = getXmlResponseNode(req.responseXML);
        
        if ((rootNode) && (rootNode.hasChildNodes())) {
            var currentTrack = rootNode.firstChild;
            var newHTML = "<b>Coming Up:</b><br />";
            while (currentTrack) {
                var trackName = getNodeText(currentTrack.getElementsByTagName("name")[0]);
                var artistName = getNodeText(currentTrack.getElementsByTagName("artistName")[0]);
        
                
                newHTML += trackName + "-" + artistName + "<br />";
                currentTrack = currentTrack.nextSibling;
            }
        }
        else {
            newHTML = "";
        }
        if (newHTML != oThis._lastQueueHTML) {
            element.innerHTML = newHTML;
            oThis._lastQueueHTML = newHTML;
        }
    };
    var req = new Ajax.Request("/ws/queue", 
        {
            method: "post",
            onComplete: f
        });
}

Exit66Jukebox.prototype.requestHandler = function(requestType, id) {
    var oThis = this;
    var f =  function(req) {
        var rootNode = getXmlResponseNode(req.responseXML);
        var message = "Thanks for requesting a song!";
        if ((rootNode) && (rootNode.hasChildNodes())) {
            message = getNodeText(rootNode.getElementsByTagName("message")[0]);
        }
        alert(message);
        loadQueue();
    };
    var req = new Ajax.Request("/ws/request/" + requestType + "/" + id, 
        {
            method: "post",
            onComplete: f
        });
}


Exit66Jukebox.prototype.requestTrack = function(trackId) {
    this.requestHandler("addtrack", trackId);
}

Exit66Jukebox.prototype.requestAlbum = function(albumId) {
    this.requestHandler("addalbum", albumId);
}

Exit66Jukebox.prototype.requestArtist = function(artistId) {
    this.requestHandler("addartist", artistId);
}

Exit66Jukebox.prototype._getClearBreak = function() {
    var clearBreak = document.createElement('hr');
    clearBreak.style.clear = 'both';
    clearBreak.style.display = 'block';
    clearBreak.style.height = '1px';
    clearBreak.style.margin = '0';
    clearBreak.style.visibility = 'hidden';
    return clearBreak;
}

function removeChild(parent, child) {
    //new Effect.Fade(child)
    parent.removeChild(child);
}

function getXmlResponseNode(xml) {
    var node = xml.firstChild;
    while (node) {
        if (node.tagName == 'response') {
            return node;
        }
        node = node.nextSibling;
    }
}

function getNodeText(node) {
    if (window.ActiveXObject) {
        return node.text;
    }
    else if (navigator.userAgent.toLowerCase().indexOf("opera") > -1) {
        return node.innerText;
    }
    else {
        return node.textContent;
    }
}

function createElement(type, name) {
   var element = null;
   // First try the IE way; if this fails then use the standard way
   try {
      element = document.createElement('<'+type+' name="'+name+'">');
   } catch (e) {
      // Probably failed because we're not running on IE
   }
   if (!element) {
      element = document.createElement(type);
      element.name = name;
   }
   return element;
}

var errFunc = function(t) {
    alert('Error ' + t.status + ' -- ' + t.statusText);
}

function replace(s, t, u) {
  /*
  **  Replace a token in a string
  **    s  string to be processed
  **    t  token to be found and removed
  **    u  token to be inserted
  **  returns new String
  */
  i = s.indexOf(t);
  r = "";
  if (i == -1) return s;
  r += s.substring(0,i) + u;
  if ( i + t.length < s.length)
    r += replace(s.substring(i + t.length, s.length), t, u);
  return r;
}